package com.xuecheng.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

public class AuthFilter implements Ordered, GlobalFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    * 过滤拦截token
    * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.放行部分URI(有些请求不登录也能访问)
        String path = request.getURI().getPath();
        if(path.contains("coursePub/preview") || path.contains("/auth/login") ||
         path.contains("basic/dictionary") || path.contains("category/tree-nodes") ||
         path.contains("course/ipload") || path.contains("search") || path.contains("payment/wx/notify")){
            return chain.filter(exchange);
        }
        //3.获取请求头token
        String token = request.getHeaders().getFirst("Authorization");
        //4.校验token
        Boolean verifyToken = JwtUtils.verifyToken(token);
        if(verifyToken == false){
            response.setRawStatusCode(401);//权限不足,跳转到登录页
            return response.setComplete();//直接拦截,并返回
        }
        //5.解析token
        AuthInfo authInfo = JwtUtils.getInfoFromToken(token);
        //6.判断token是否过期
        if(!redisTemplate.hasKey(UserConstants.USER_ID+authInfo.getUid())){
            response.setRawStatusCode(401);//权限不足,跳转到登录页
            return response.setComplete();//直接拦截,并返回
        }
        //7.判断小于1小时,续期
        Long expire = redisTemplate.getExpire(UserConstants.USER_ID + authInfo.getUid(), TimeUnit.HOURS);
        if(expire<1){
            redisTemplate.expire(UserConstants.USER_ID+authInfo.getUid(),3,TimeUnit.HOURS);
        }
        try {
            //8.将authInfo转为hjson,设置到payload请求头,实现路由转发
            String json = JSON.toJSONString(authInfo);
            //8.解决中文乱码问题
            String encode = URLEncoder.encode(json, "UTF-8");
            ServerHttpRequest newRequest = request.mutate().header("payload", encode).build();
            //将newRequest设置到exchange
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            //9.放行
            return chain.filter(newExchange);
        }catch (UnsupportedEncodingException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
